﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using VoiceTestPlatform.Infrastrature;

namespace VoiceTestPlatform
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
           
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            this.Exit += App_Exit;
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            SoundManager.ClosePlayer();
        }

        void App_Exit(object sender, ExitEventArgs e)
        {
            SoundManager.ClosePlayer();
            Log.Save();
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            SoundManager.ClosePlayer();
           

            string cd = ParameterManager.RunDir;
            string sp = Path.Combine(cd, "ErrorLog");
            if (!Directory.Exists(sp))
            {
                Directory.CreateDirectory(sp);
            }
            string df = Path.Combine(sp, DateTime.Now.ToString("yyyyMMddHHmmss") + ".log");
            //File.Move(lastpath, df);
            MessageBox.Show("程序出错，详见运行目录下ErrorLog文件夹" + df);
            using (FileStream NewText = File.Create(df))
            {
                using (StreamWriter fileWriter = new StreamWriter(NewText))
                {
                    fileWriter.Write(GetRealExceptionMsg((e.ExceptionObject as Exception)));
                }
            }
        }

        private string GetRealExceptionMsg(Exception ex)
        {
            if (ex == null)
            {
                return string.Empty;
            }
            if (ex.InnerException != null)
            {
                return GetRealExceptionMsg(ex.InnerException);
            }
            return ex.Message + "\n\r" + ex.StackTrace.ToString();

        }


        protected override void OnStartup(StartupEventArgs e)
        {
            DefaultWindowsService.Regsiter(typeof(AddProjectItemViewModel), typeof(AddProjectItemWindow));
            DefaultWindowsService.Regsiter(typeof(RecordViewModel), typeof(RecordWindow));
            DefaultWindowsService.Regsiter(typeof(NetworkStatusViewModel), typeof(NetworkStatusWindow));
            DefaultWindowsService.Regsiter(typeof(ArtificialViewModel), typeof(ArtificialWindow));
            DefaultWindowsService.Regsiter(typeof(ParameterViewModel), typeof(ParameterWindow));
            base.OnStartup(e);
        }

    }
}
